//
//  UKCollectionViewProxy.m
//  UKListManager
//
//  Created by ET|冰琳 on 16/11/4.
//  Copyright © 2016年 UK. All rights reserved.
//

#import "UKCollectionViewProxy.h"

@interface UKCollectionViewProxy ()

@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, assign) BOOL  cacheHeight;
@property (nonatomic, assign) id<UKListDataSource>  dataSource;
@property (nonatomic, copy) ListCellConfiguration cellConfiguration;
@property (nonatomic, copy  , nullable) ListItemSelect selectItem;

@end

@implementation UKCollectionViewProxy

- (instancetype)initWithIdentifier:(NSString *)identifier
                       cacheHeight:(BOOL)cache
                        dataSource:(id<UKListDataSource>)dataSource
                        cellConfig:(ListCellConfiguration)cellConfig{
    
    if (self = [super init]) {
        self.identifier = identifier;
        self.cacheHeight = cache;
        self.dataSource = dataSource;
        self.cellConfiguration = cellConfig;
    }
    return self;
}

- (void)setSelectItemAction:(ListItemSelect)selectItemAction{
    self.selectItem = selectItemAction;
}

#pragma mark - UICollectionViewDataSource 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = [self identifierForIndexPath:indexPath];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [self _configurationCell:cell atIndexPath:indexPath];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.dataSource rowCountAtSection:section];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [self.dataSource sectionCount];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectItem) {
        self.selectItem([self.dataSource dataAtIndexPath:indexPath], indexPath);
    }
}

#pragma mark - private
- (void)_configurationCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{
    
    id dataAtIndex = [self.dataSource dataAtIndexPath:indexPath];
    
    if ([cell conformsToProtocol:@protocol(CellBinder)]) {
        id<CellBinder> binder = (id<CellBinder>)cell;
        [binder bindWithViewModel:dataAtIndex];
    }
    
    if (self.cellConfiguration) {
        self.cellConfiguration(cell,dataAtIndex, indexPath);
    }
}

- (NSString *)identifierForIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = self.identifier;
    if (self.identifierDelegate) {
        identifier = [self.identifierDelegate identifierForCellAtIndexPath:indexPath];
    }
    return identifier;
}

@end
